import { throttle } from "@/utils/helper"
import { usePageScroll } from "@tarojs/taro"
import { useRef, useState } from "react"

/**
 * 页面自定义导航栏 导航栏背景色透明度
 */
export function useNavigationOpacity(): [opacity: number, scrollHandler: (scrollTop: number) => void] {
  const [opacity, setOpacity] = useState(0)
  const updateOpacity = useRef(
    throttle(30, (scrollTop: number) => {
      const needle = 120
      const _opacity = Math.min(scrollTop, needle) / needle
      setOpacity(_opacity)
    }, { noLeading: false })
  )
  const scrollHandler = updateOpacity.current
  usePageScroll(({ scrollTop }) => {
    updateOpacity.current(scrollTop)
  })
  // @ts-ignore
  return [opacity, scrollHandler]
}
